package com.it.nongchanping.controller;

import com.it.nongchanping.entity.Announcement;
import com.it.nongchanping.service.AnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/admin/announcement")
public class AdminAnnouncementController {

    @Autowired
    private AnnouncementService announcementService;

    @GetMapping("")
    public String listAnnouncements(Model model) {
        List<Announcement> announcementList = announcementService.getAllAnnouncements();
        model.addAttribute("announcementList", announcementList);
        model.addAttribute("title", "公告管理");
        model.addAttribute("activePage", "announcement");
        return "admin/announcement/list";
    }

    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("announcement", new Announcement());
        model.addAttribute("title", "添加新公告");
        model.addAttribute("activePage", "announcement");
        return "admin/announcement/form";
    }

    @PostMapping("/save")
    public String saveAnnouncement(@ModelAttribute Announcement announcement, RedirectAttributes redirectAttributes) {
        if (announcement.getId() == null) {
            announcementService.saveAnnouncement(announcement);
        } else {
            announcementService.updateAnnouncement(announcement);
        }
        redirectAttributes.addFlashAttribute("message", "公告保存成功！");
        return "redirect:/admin/announcement";
    }

    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, Model model) {
        Announcement announcement = announcementService.getAnnouncementById(id);
        model.addAttribute("announcement", announcement);
        model.addAttribute("title", "编辑公告");
        model.addAttribute("activePage", "announcement");
        return "admin/announcement/form";
    }

    @GetMapping("/delete/{id}")
    public String deleteAnnouncement(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        announcementService.deleteAnnouncement(id);
        redirectAttributes.addFlashAttribute("message", "公告删除成功！");
        return "redirect:/admin/announcement";
    }
} 